package com.skycong.hello77.common.okhttp3;

import android.app.DownloadManager;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * 请求的发送，请求参数的配置，https的支持
 * Created by Kiki on 2018/6/15.
 */

public class CommonOkHttpClient {
    private static final int TIME_OUT = 30;//超时参数
    private static OkHttpClient okHttpClient;

    //static代码块是在构造函数之前执行的，而且只执行一次，即类首次加载时
    //静态代码块是自动执行的，在项目启动时就执行
    //类级别的初始化，只是在类加载的时候做一次
    /**
     * 为client去配置参数
     */
    static {
        //创建client对象的构建着
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient().newBuilder();
        //为构建着填充超时时间
        okHttpBuilder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpBuilder.readTimeout(TIME_OUT,TimeUnit.SECONDS.SECONDS);
        okHttpBuilder.writeTimeout(TIME_OUT,TimeUnit.SECONDS);

        //确保支持重定向
        okHttpBuilder.followRedirects(true);

        //https支持
        okHttpBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
//        okHttpBuilder.sslSocketFactory(okHttpClient.getSslSocketFactory());
              //生成我们client对象
        okHttpClient = okHttpBuilder.build();
    }

    public static Call sendRequest(Request request,CommonJsonCallback commonCallback){
        Call call = okHttpClient.newCall(request);
        call.enqueue(commonCallback);
        return call;
    }
}
